package com.bw.controller;

import com.bw.common.JwtUtils;
import com.bw.common.Md5Utils;
import com.bw.entity.User;
import com.bw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
public class LoginController {


    @Autowired
    UserService userService;



    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/loginPage.do")
    public String loginPage(){
        return "login";
    }

    /**
     * 执行登录
     * @return
     */
    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model, HttpServletResponse response){
        // 验证非空
        if (result.hasErrors()){
            // 如果参数有异常， 随机取出一条
            String defaultMessage = result.getAllErrors().get(0).getDefaultMessage();
            model.addAttribute("error",defaultMessage);
            return "login";
        }
        // 用户名是否存在

        User userFromDB = userService.selectByName(loginUser.getName());
        if (userFromDB == null){
            model.addAttribute("error","用户名不存在");
            return "login";
        }

        // 校验密码
        //12345
        String loginUserPassword = loginUser.getPassword();// 用户输入的密码 12345
        String dbPassword = userFromDB.getPassword();// 数据库里的密码乱码 d009e56f212a5a72904c6a43861d5e6e
        String dbSalt = userFromDB.getSalt();// 数据库里的盐 cd8b6d88
        // 加密用户输入的密码和数据库里的盐
        String md5String = Md5Utils.getMD5String(loginUserPassword + dbSalt);

        if (!md5String.equals(dbPassword)){
            model.addAttribute("error","密码错误");
            return "login";
        }
        // 加密用户信息 得到令牌
        userFromDB.setPassword("");
        String token = JwtUtils.createToken(userFromDB);

        // 把token放入cookie
        Cookie cookie = new Cookie("currentUserToken", token);

        // 把cookie响应给浏览器
        response.addCookie(cookie);
        model.addAttribute("userName",userFromDB.getName());
        return "success";
    }
}
